//
//  AlipayRechargeViewController.m
//  PlayBall
//
//  Created by Edward Zhang on 12-5-9.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "JddAlipayRechargeViewController.h"
#import "JddSecurity.h"
//#import "AlixPayOrder.h"
//#import "AlixPayResult.h"
//#import "AlixPay.h"
//#import "DataSigner.h"
#import "JddViewControllerManager.h"
#import "JddUserProfile.h"
#import "SBJson.h"
#import "JddQueryAlipayOperation.h"
#import "AppDelegate.h"
#import "HUD.h"
@interface JddAlipayRechargeViewController (){
    AppDelegate *appDelegate;
    UILabel *label;
}

@end

@implementation JddAlipayRechargeViewController

SHARED_VIEW_CONTROLLER_IMPLEMENT(JddAlipayRechargeViewController);

@synthesize userNameLabel;
@synthesize mobileTextField;
@synthesize amountTextField;

- (NSString *)generateTradeNO
{
	const int N = 15;
	
	NSString *sourceString = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	NSMutableString *result = [[NSMutableString alloc] init];
	srand(time(0));
	for (int i = 0; i < N; i++)
	{   
		unsigned index = rand() % [sourceString length];
		NSString *s = [sourceString substringWithRange:NSMakeRange(index, 1)];
		[result appendString:s];
	}
	return result;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
	if (alertView.tag == 123) {
		NSString * URLString = @"http://itunes.apple.com/cn/app/id535715926?mt=8";
		[[UIApplication sharedApplication] openURL:[NSURL URLWithString:URLString]];
	}
}

- (NSString *)urlEncodedString:(NSData *)src
{    
    char *hex = "0123456789ABCDEF";
	unsigned char * data = (unsigned char*)[src bytes];
	int len = [src length];
	NSMutableString* s = [NSMutableString string];
	for(int i = 0;i<len;i++){
		unsigned char c = data[i];
		if( ('a' <= c && c <= 'z')
		   || ('A' <= c && c <= 'Z')
		   || ('0' <= c && c <= '9') ){
			NSString* ts = [[NSString alloc] initWithCString:(char *)&c length:1];
			
			[s appendString:ts];
		} else {
			[s appendString:@"%"];
			char ts1 = hex[c >> 4];
			NSString* ts = [[NSString alloc] initWithCString:&ts1 length:1];
			[s appendString:ts];
			char ts2 = hex[c & 15];
			ts = [[NSString alloc] initWithCString:&ts2 length:1];
			[s appendString:ts];
			
		}
	}
	return s;
}


-(void)QueryAlipayOperationResult:(NSData *)result{
    [JddCommonFunction setWaitingViewHidden:YES fromController:self];
    SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
    NSDictionary *dictResult = [jsonParser objectWithData:result];
    NSInteger code = [[dictResult objectForKey:@"Code"] intValue];
    NSString *data = [dictResult objectForKey:@"Data"];
    if (!(code == 0 ? YES : NO)) {
        [HUD showToast:data];
        return;
    }

//    if (result) {
//        NSString *tradeNO = [JddDataParser parseBuyHistoryDetailResult:result];
//        NSString *partner = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"Partner"];
//        NSString *seller = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"Seller"];
//        AlixPayOrder *order = [[AlixPayOrder alloc] init];
//        order.partner = partner;
//        order.seller = seller;
//        order.tradeNO = tradeNO; //订单ID（由商家自行制定）
//        order.productName = @"玩球球手机充值";
//        order.productDescription = @"玩球球ios支付宝充值";
//        order.amount = amountTextField.text; //商品价格
//        order.notifyURL = ALI_PAY_NOTIFY_URL;//[self urlEncodedString:[NOTIFY_URL dataUsingEncoding:NSUTF8StringEncoding]]; //回调URL
//        //应用注册scheme,在AlixPayDemo-Info.plist定义URL types,用于安全支付成功后重新唤起商户应用
//        NSString *appScheme = @"JiangDuoDuo-IOS";  
//        //将商品信息拼接成字符串
//        NSString *orderSpec = [order description];
//        NSLog(@"orderSpec = %@",orderSpec);
//        
//        //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
//        id<DataSigner> signer = CreateRSADataSigner([[NSBundle mainBundle] objectForInfoDictionaryKey:@"RSA private key"]);
//        NSLog(@"1111 = %@",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"RSA private key"]);
//        NSString *signedString = [signer signString:orderSpec];
//        
//        //将签名成功字符串格式化为订单字符串,请严格按照该格式
//        NSString *orderString = nil;
//        if (signedString != nil) {
//            orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
//                           orderSpec, signedString, @"RSA"];
//            
//            //获取安全支付单例并调用安全支付接口
//            AlixPay * alixpay = [AlixPay shared];
//            int ret = [alixpay pay:orderString applicationScheme:appScheme];
//            
//            if (ret == kSPErrorAlipayClientNotInstalled) {
//                UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" 
//                                                                     message:@"您还没有安装支付宝的客户端，请先装。" 
//                                                                    delegate:self 
//                                                           cancelButtonTitle:@"确定" 
//                                                           otherButtonTitles:nil];
//                [alertView setTag:123];
//                [alertView show];
//
//            }
//            else if (ret == kSPErrorSignError) {
//                NSLog(@"签名错误！");
//            }
//            
//        }
//    }
}

- (IBAction)rechargeButtonClicked:(id)sender{
    if (![amountTextField.text length]) {
        [JddCommonFunction messageBoxWithMessage:@"请输入金额"];
        return;
    }
    else if ([amountTextField.text intValue]<1) {
        [JddCommonFunction messageBoxWithMessage:@"每次充值不能少于1彩豆"];
        return;
    }
     [JddCommonFunction setWaitingViewHidden:NO fromController:self];
    JddQueryAlipayOperation *operation = [[JddQueryAlipayOperation alloc] init];
    operation.delegate = self;
    operation.Money =[NSNumber numberWithInt:[amountTextField.text intValue]];
    [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
    
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)backfirst:(id)sender{
    [amountTextField resignFirstResponder];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
//    [self.navigationItem setTitle:PAGE_ALIPAY_RECHARGE];
        UILabel *customLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 30)];
        customLab.backgroundColor = [UIColor clearColor];
        [customLab setText:PAGE_ALIPAY_RECHARGE];
        customLab.textAlignment = NSTextAlignmentCenter;
        [customLab setTextColor:[UIColor whiteColor]];
        customLab.font = [UIFont systemFontOfSize:19];
        self.navigationItem.titleView = customLab;
        
//        //self.navigationItem.hidesBackButton = YES;
    
        appDelegate=[[UIApplication sharedApplication] delegate];
}

- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)createlabel
{
    label = [[UILabel alloc] initWithFrame:CGRectMake(20, 180, 320, 40)];
    label.text = [NSString stringWithFormat:@"充值%@彩豆，送红包%@彩豆!",appDelegate.moneyNum,appDelegate.redNum];
    label.textColor = [UIColor colorWithRed:140/255.0f green:140/255.0f blue:140/255.0f alpha:1];
    [self.view addSubview:label];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"ChongZhi"];
    [MobClick event:@"UserCenter-AlipayChongzhi"];
    self.userNameLabel.text = [JddUserProfile sharedInstance].name;
    amountTextField.userInteractionEnabled = YES;
    self.amountTextField.text = appDelegate.moneyNum;
    if ([appDelegate.redNum length]!= 0 ) {
        [self createlabel];
        amountTextField.userInteractionEnabled = NO;
    }

}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"ChongZhi"];

    amountTextField.text = @"";
    [amountTextField resignFirstResponder];
    [label removeFromSuperview];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
